package com.atguigu.eduorder.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.eduorder.entity.Order;
import com.atguigu.eduorder.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author 粟德桡
 * @since 2021-11-29
 */
@RestController
@RequestMapping("/eduorder/order")
@CrossOrigin
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;
    //根据课程id和用户id创建订单，返回订单id
    @PostMapping("createOrder/{courseId}")
    public R save(@PathVariable String courseId, HttpServletRequest request) {
        boolean b = JwtUtils.checkToken(request);
        if(!b){
            log.info("未登录");
            return R.error().code(28004).message("请先登录");
        }

        if(StringUtils.isEmpty(courseId)){
            return R.error();
        }
        String orderId = orderService.saveOrder(courseId, JwtUtils.getMemberIdByJwtToken(request));
        return R.ok().data("orderId", orderId);
    }

    @GetMapping("getOrder/{orderId}")
    public R getOrderInfo(@PathVariable String orderId){
        if(StringUtils.isEmpty(orderId)){
            return R.error();
        }
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNo, orderId)
        );

        return R.ok().data("item",order);
    }

    @GetMapping("isBuyCourse/{memberid}/{id}")
    public boolean isBuyCourse(@PathVariable String memberid,
                               @PathVariable String id) {
        if(StringUtils.isEmpty(memberid)){
            log.info("memberid为空");
            return false;
        }
        if(StringUtils.isEmpty(id)){
            log.info("id为空");
            return false;
        }

        //订单状态是1表示支付成功
        int count = orderService.count(new QueryWrapper<Order>().eq("member_id", memberid).eq("course_id", id).eq("status", 1));
        if(count>0) {
            return true;
        } else {
            log.info("未支付");
            return false;
        }
    }

}

